package cn.gov.pbc.gd.credit.center.service.query.impl;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.liu.jbase.ResultVo;
import com.liu.tools.DateUtil;
import com.liu.tools.FileUtil;
import com.liu.tools.LogUtil;
import com.liu.tools.StrUtil;

import cn.gov.pbc.gd.credit.center.service.query.ICCQueryService;
import cn.gov.pbc.gd.credit.center.service.util.AgentUtil;
import cn.gov.pbc.gd.credit.center.service.util.JsoupUtil;
import cn.gov.pbc.gd.credit.common.constant.CodeConstant;
import cn.gov.pbc.gd.credit.common.constant.ConfConstant;
import cn.gov.pbc.gd.credit.vo.center.query.ReqCCApplyTblVo;
import cn.gov.pbc.gd.credit.vo.center.query.ReqCCCreditReportVo;
import cn.gov.pbc.gd.credit.vo.center.query.ReqCCJusticeVo;
import cn.gov.pbc.gd.credit.vo.center.query.ReqFirstStepVo;
import cn.gov.pbc.gd.credit.vo.center.query.ReqSecondStepVo;
import cn.gov.pbc.gd.credit.vo.center.query.ResCCApplyTblVo;
import cn.gov.pbc.gd.credit.vo.center.query.ResCCCreditReportVo;
import cn.gov.pbc.gd.credit.vo.center.query.ResCCJusticeVo;
import cn.gov.pbc.gd.credit.vo.center.query.ResFirstStepVo;
import cn.gov.pbc.gd.credit.vo.center.query.ResSecondStepVo;

@Service
public class CCQueryServiceImpl implements ICCQueryService{

	private static Logger logger = LoggerFactory.getLogger(CCQueryServiceImpl.class);
	
	
	@Override
	public ResultVo<ResFirstStepVo> queryFirstStep(ReqFirstStepVo vo, HttpServletRequest request) {

		///branchquery/innerQueryChargeAction.do?forwardtype=4&nexttype=1&querytype=24&
		//user=������&ctype=0&idno=412822198212021417&reltel=&relname=&relcerttype=&relcertno=

		ResultVo<ResFirstStepVo> resultVo = new ResultVo<>();
		
		if(vo == null || StrUtil.isNull(vo.getIdno(), vo.getUser())){
			
			logger.error(LogUtil.msg("CCQueryServiceImpl:queryFirstStep", "请求参数不正确"));
			resultVo.setCode(CodeConstant.REQ_PARAM_FAIL);
			resultVo.setMsg("查询用户征信第一步，请求参数不正确");
			return resultVo;
		}
		
		String data = vo.toString();
		logger.debug(LogUtil.msg("CCQueryServiceImpl:queryFirstStep", "查询用户征信第一步请求数据：" + data));
		
		String requestUrl = ConfConstant.ccDomainUrl + ConfConstant.ccQueryAndChargeUrl + "?" + data;
		logger.debug(LogUtil.msg("CCQueryServiceImpl:queryFirstStep", "查询用户征信第一步请求url：" + requestUrl));
		
		Document document = null; 
		String sourceHtml = "";
		
		try {
			
			 
			 if(StrUtil.isNotNull(ConfConstant.ccTestPath)){
			 
				 document = Jsoup.parse(new File(ConfConstant.ccTestPath + "个人查询-第二步(收费界面).html"), "UTF-8");
			 
			 } else {
	     
				 document = JsoupUtil.get(requestUrl, "utf-8", vo.getCookies());
				 logger.debug(LogUtil.msg("CCQueryServiceImpl:queryFirstStep", "查询用户征信第一步请求结果：" + document.html()));
				 
			 }
			 
			 if(document == null){
				
				 logger.error(LogUtil.msg("CCQueryServiceImpl:queryFirstStep", "征信中心第一步查询，征信中心没有返回任何信息"));
				 resultVo.setCode(CodeConstant.FAIL);
				 resultVo.setMsg("查询征信中心（第一步）内容为空");
				 return resultVo;
			 }
			 
			 sourceHtml = document.html();
			 if(sourceHtml.indexOf("无法取得用户登录信息 ") != -1){
				 resultVo.setCode(CodeConstant.CREDIT_NO_LOGIN);
				 resultVo.setMsg("登录超时，请重新登录系统");
				 logger.error(LogUtil.msg("CCQueryServiceImpl:queryFirstStep", "征信中心第一步查询，征信中心错误：无法取得用户登录信息"));
				 return resultVo;
			 }
			 ResFirstStepVo resFirstStepVo = new ResFirstStepVo();
		     
		     //收费需要收费
		     String script = document.getElementsByTag("script").html();
		     int index = script.indexOf("secondchargestat");
		     String sub = script.substring(index,index + 25);
		     logger.info(LogUtil.msg("CCQueryServiceImpl:queryFirstStep", "收费信息标识：" + sub));
		     String regEx="[^0-9]";   
		     Pattern p = Pattern.compile(regEx);   
		     Matcher m = p.matcher(sub);   
		     resFirstStepVo.setIsFee(Integer.parseInt(m.replaceAll("").trim()));
		     
		     //提示信息
		     int beginIndex = script.indexOf("font");
		     int endIndex = script.indexOf("</font>");
		     String tipHtml = script.substring(beginIndex-1, endIndex + "</font>".length());
		     String tipMsg = Jsoup.parse(tipHtml).text();
		     resFirstStepVo.setTipMsg(tipMsg);
		     
		     String queryNum = document.getElementById("querynumber").attr("value");
		     logger.info(LogUtil.msg("CCQueryServiceImpl:queryFirstStep", "查询次数：" + queryNum));
		     if(StrUtil.isNull(queryNum)){
		    	 queryNum = "0";
		     }
		     resFirstStepVo.setQueryNum(Integer.parseInt(queryNum));
		     
		     String chargeStat = document.getElementById("chargestathidden").attr("value");
		     logger.info(LogUtil.msg("CCQueryServiceImpl:queryFirstStep", "chargeStat：" + chargeStat));
		     if(StrUtil.isNull(chargeStat)){
		    	 chargeStat = "";
		     }
		     resFirstStepVo.setChargeStat(chargeStat);
		     
		     String historyChargeStat = document.getElementById("historychargestat").attr("value");
		     logger.info(LogUtil.msg("CCQueryServiceImpl:queryFirstStep", "historyChargeStat：" + historyChargeStat));
		     if(StrUtil.isNull(historyChargeStat)){
		    	 historyChargeStat = "0";
		     }
		     resFirstStepVo.setHistoryChargeStat(historyChargeStat);
		     
		     String queryLog = document.getElementById("querylog").attr("value");
		     logger.info(LogUtil.msg("CCQueryServiceImpl:queryFirstStep", "queryLog：" + queryLog));
		     if(StrUtil.isNull(queryLog)){
		    	 queryLog = "";
		     }
		     resFirstStepVo.setQuerylog(queryLog);
		     
		     resFirstStepVo.setQuerytype(vo.getQuerytype());
		     //resFirstStepVo.set
		     
		     String regx = "(.)*?的历史计费查询记录";
		     
		     String str = document.getElementsMatchingText(regx).text();
		     
		     if(StrUtil.isNotNull(str)){//判断是否有查询记录
		    	 
			     Elements  elements = document.getElementById("step2").select("table");
			     
			     elements = elements.get(0).getElementsByTag("tr");
			     elements.remove(elements.size() - 1);
			     elements.remove(elements.size() - 1);
			     elements.remove(0);
			     elements.remove(0);
			     elements.remove(0);
			     elements.remove(0);
			     elements.remove(0);
			     //System.err.println(elements.get(0));
			     List<Map<String, String>> list = new ArrayList<>();
			     for (Element element : elements) {
			    	 Elements tdElements = element.select("td");
			    	 tdElements.remove(0);
			    	 Map<String, String> map = new HashMap<>();
			    	 int i = 0;
			    	 for (Element subEle : tdElements) {
			    		 if(i == 0){
			    			 map.put("queryCorp", subEle.text());
			    		 } else {
							 map.put("queryTime", subEle.text());
						 }		    		 
			    		 i ++;
					 }
			    	 list.add(map);
				 }
			     
			     resFirstStepVo.setList(list);
		     }
		     
			 resultVo.setCode(CodeConstant.SUCCESS);
			 resultVo.setData(resFirstStepVo);
			 
		} catch (Exception e) {
			
			String fileName = "first_" + vo.getIdno() + "_" + DateUtil.format(new Date(), DateUtil.FORMAT_ALL_DAY) + ".html";
			FileUtil.dataToFile(sourceHtml, ConfConstant.fileQueryErrorPath + fileName);
			
			logger.error(LogUtil.msg("CCQueryServiceImpl:queryFirstStep", "征信中心第一步查询解析异常"), e);
			resultVo.setCode(CodeConstant.EXCEPTION);
			resultVo.setMsg("征信中心第一步查询解析异常");
			return resultVo;
		}
		
		return resultVo;
		
	}

	@Override
	public ResultVo<ResSecondStepVo> querySecondStep(ReqSecondStepVo vo, HttpServletRequest request) {

		ResultVo<ResSecondStepVo> resultVo = new ResultVo<>();
		
		if(vo == null ||  StrUtil.isNull(vo.getCertno(), vo.getName())){
			
			logger.error(LogUtil.msg("CCQueryServiceImpl:querySecondStep", "请求参数不正确"));
			resultVo.setCode(CodeConstant.REQ_PARAM_FAIL);
			resultVo.setMsg("查询用户征信第二步，请求参数不正确");
			return resultVo;
		}
		
		String data = vo.toParams();
		logger.debug(LogUtil.msg("CCQueryServiceImpl:querySecondStep", "查询用户征信第二步请求数据：" + data));
		String requestUrl = ConfConstant.ccDomainUrl + ConfConstant.ccQueryCreditSecondUrl;
		logger.debug(LogUtil.msg("CCQueryServiceImpl:querySecondStep", "查询用户征信第二步请求URL：" + requestUrl));
		
		Document document = null; 
		String sourceHtml = "";
		
		try {
			 
			 if(StrUtil.isNotNull(ConfConstant.ccTestPath)){
			 
				 document = Jsoup.parse(new File(ConfConstant.ccTestPath + "个人查询第三步（确认并打印申请表）.html"), "UTF-8");
			 
			 } else {

				 document = JsoupUtil.post(requestUrl, data, "GBK", vo.getCookies());
				 logger.debug(LogUtil.msg("CCQueryServiceImpl:querySecondStep", "查询用户征信第二步请求结果：" + document.html()));
			 }
			 
			 if(document == null){
					
				 logger.error(LogUtil.msg("CCQueryServiceImpl:querySecondStep", "征信中心第二步查询，征信中心没有返回任何信息"));
				 resultVo.setCode(CodeConstant.FAIL);
				 resultVo.setMsg("查询征信中心（第二步）内容为空");
				 return resultVo;
			 }
			 
			 sourceHtml = document.html();
			 
		     
			 ResSecondStepVo resSecondStepVo = new ResSecondStepVo();
			 
			 Elements elements = document.getElementsByTag("script");
		     String script = elements.html();
		     int index = script.indexOf("dissentid\").val(") + "dissentid\").val(\"".length();
		     String dissentid = "";
		     if(index != -1){
			     dissentid = script.substring(index , index + "201706024401240400338_febea38409b6e7d2907d74125d4aeedd".length());
			     resSecondStepVo.setDissentid(dissentid);
		     }
		     logger.debug(LogUtil.msg("CCQueryServiceImpl:querySecondStep", "解析dissentid结果：" + dissentid + ", index=" + index));
		     index = script.indexOf("chargeNOHidden\").val(") + "chargeNOHidden\").val(\"".length();
		     String chargeNOHidden = "";
		     if(index != -1){
			     chargeNOHidden = script.substring(index , index + "G2017071800000116070215".length());
			     resSecondStepVo.setChargeNo(chargeNOHidden);
		     }
		     logger.debug(LogUtil.msg("CCQueryServiceImpl:querySecondStep", "解析chargeNOHidden结果：" + dissentid + ", index=" + index));
//		     Element element = document.getElementById("dissentid");
//		     if(element != null){
//		    	 resSecondStepVo.setDissentid(element.attr("value"));
//		     }
//		     
//		     element = document.getElementById("chargeNOHidden");
//		     if(element != null){
//		    	 resSecondStepVo.setChargeNo(element.attr("value"));
//		     }
		     
		     
   		     String queryLog = document.getElementById("querylog").attr("value");
		     logger.info(LogUtil.msg("CCQueryServiceImpl:querySecondStep", "queryLog：" + queryLog));
		     if(StrUtil.isNull(queryLog)){
		    	 queryLog = "";
		     }
		     
		     resSecondStepVo.setVertype(vo.getQuerytype());
		     
		     resultVo.setData(resSecondStepVo);
		     resultVo.setCode(CodeConstant.SUCCESS);
			 
		} catch (Exception e) {
			
			String fileName = "second_" + vo.getId() + "_" + DateUtil.format(new Date(), DateUtil.FORMAT_ALL_DAY) + ".html";
			FileUtil.dataToFile(sourceHtml, ConfConstant.fileQueryErrorPath + fileName);
			
			logger.error(LogUtil.msg("CCQueryServiceImpl:querySecondStep", "征信中心第二步查询解析异常"), e);
			resultVo.setCode(CodeConstant.EXCEPTION);
			resultVo.setMsg("征信中心第二步查询解析异常");
			return resultVo;
		}
		
		return resultVo;
	}

	@Override
	public ResultVo<ResCCApplyTblVo> applyTbl(ReqCCApplyTblVo vo, HttpServletRequest request) {

		ResultVo<ResCCApplyTblVo> resultVo = new ResultVo<>();
		
		if(vo == null || StrUtil.isNull(vo.getIdno(), vo.getUser(), vo.getDissentid())){
			
			logger.error(LogUtil.msg("CCQueryServiceImpl:applyTbl", "请求参数不正确"));
			resultVo.setCode(CodeConstant.REQ_PARAM_FAIL);
			resultVo.setMsg("获取申请表请求参数不正确");
			return resultVo;
		}

		String data = vo.toParams();
		logger.debug(LogUtil.msg("CCQueryServiceImpl:applyTbl", "获取查询申请表请求数据：" + data));
		
		String requestUrl = ConfConstant.ccDomainUrl + ConfConstant.ccPrintApplyTableUrl + "?" + data;
		logger.debug(LogUtil.msg("CCQueryServiceImpl:applyTbl", "获取查询申请表请求url：" + requestUrl));
		Document document = null;
		String sourceHtml = "";
		for (int i = 0; i < 2; i++) {
			try {
				 			
				if(StrUtil.isNotNull(ConfConstant.ccTestPath)){
				 
					 document = Jsoup.parse(new File(ConfConstant.ccTestPath + "打印申请表.html"), "UTF-8");
				 
				 } else {
		     
					 document = JsoupUtil.get(requestUrl, "GBK", vo.getCookies());
					 logger.debug(LogUtil.msg("CCQueryServiceImpl:applyTbl", "获取查询申请表结果：" + document.html()));
					 
				 }
			     
				 if(document == null){
					
					 if(i == 0){
						 continue;
					 }
					 logger.error(LogUtil.msg("CCQueryServiceImpl:applyTbl", "征信中心查询申请表，征信中心没有返回任何信息"));
					 resultVo.setCode(CodeConstant.FAIL);
					 resultVo.setMsg("查询申请表内容为空");
					 return resultVo;
				 }
				 
				 sourceHtml = document.html();
				 
			     String regx = "个人征信信用报告本人查询申请表";
			     
			     String str = document.getElementsMatchingText(regx).text();
			     
			     if(StrUtil.isNull(str)){//判断是否有查询记录
			    	 if(i == 0){
						 continue;
					 }
			    	 logger.error(LogUtil.msg("CCQueryServiceImpl:applyTbl", "请求参数不正确"));
					 resultVo.setCode(CodeConstant.DATA_NOT_EXSIT);
					 resultVo.setMsg("获取申请表失败");
					 return resultVo;
			     }
			     
			     ResCCApplyTblVo resCCApplyTblVo = new ResCCApplyTblVo();
			    // document.getElementsByTag("script").get(0).attr("src", "resources/js/jquery-1.11.3.min.js");
			     
			     String applyNo = document.getElementsByClass("style2").get(0).text();
			     resCCApplyTblVo.setApplyNo(applyNo);
			     		  		     
			     /*增加操作员签名img start*/
			     if(StrUtil.isNotNull(vo.getOpSignName())){
				     Elements opSignEles = document.getElementsMatchingOwnText("查询用户签字");			    
				     if(opSignEles != null && opSignEles.size() > 0){
				    	Element signArea = opSignEles.get(0).parent().nextElementSibling();
				    	signArea.append("<img id='opSignNameImg' width='185' height='40' src='data:image/png;base64," + vo.getOpSignName() + "'/>");
				     }
			     }
			     /*增加操作员签名img end*/		     
			     
			     /*增加用户签名img start*/
			     Elements signEles = document.getElementsMatchingOwnText("申请人签字");			    
			     if(signEles != null && signEles.size() > 0){
			    	Element signArea = signEles.get(0).parent().nextElementSibling();
			    	signArea.append("<img style='display:none;' id='userNameImg' width='185' height='40'/>");
			     }
			     /*增加用户签名img end*/
			     
			     Element userEle = document.getElementById("user");
			     userEle.text(URLDecoder.decode(vo.getUser(),"GBK"));
			     Element userphoneEle = document.getElementById("userphone");
			     if(userphoneEle != null){
			    	 userphoneEle.text(vo.getReltel());
			     }
			     Elements elements = document.getElementsByTag("style");
			     document.getElementById("print").remove();		 
			     
			     try {
					if(StrUtil.isNotNull(vo.getRelname())){
						Element agentIns = document.getElementById("certno");
						if(agentIns != null){
							agentIns.parent().parent().after(AgentUtil.getAgentText(vo.getRelname(), vo.getRelcerttype(), vo.getRelcertno()));
						}
					 }
				} catch (Exception e) {
					logger.error(LogUtil.msg("CCQueryServiceImpl:applyTbl", "插入代理信息异常"), e);
				}
			     
			     /*修改广州分行名称*/
			     if(StrUtil.isNotNull(vo.getNote())){
				     Elements corpNoteEles = document.getElementsMatchingOwnText("中国人民银行广州分行");
				     if(corpNoteEles != null && corpNoteEles.size() > 0){
				    	corpNoteEles.get(0).text(vo.getNote());
				     }
			     }
			     String html = elements.outerHtml() + document.body().html();
			     
			     resCCApplyTblVo.setHtml(html);
			     
			     resultVo.setData(resCCApplyTblVo);
				 resultVo.setCode(CodeConstant.SUCCESS);
				 break ;
			} catch (Exception e) {
				if(i == 0){
					 continue;
				}
				String fileName = "apply_" + vo.getIdno() + "_" + DateUtil.format(new Date(), DateUtil.FORMAT_ALL_DAY) + ".html";
				FileUtil.dataToFile(sourceHtml, ConfConstant.fileQueryErrorPath + fileName);
				
				logger.error(LogUtil.msg("CCQueryServiceImpl:applyTbl", "获取查询申请表异常"), e);
				resultVo.setCode(CodeConstant.EXCEPTION);
				resultVo.setMsg("获取查询申请表异常");
				return resultVo;
			}
		} 
		return resultVo;
	}

	@Override
	public ResultVo<ResCCCreditReportVo> creditReport(ReqCCCreditReportVo vo, HttpServletRequest request) {

		ResultVo<ResCCCreditReportVo> resultVo = new ResultVo<>();
		
		if(vo == null || StrUtil.isNull(vo.getChargeNO(), vo.getName(), vo.getCertno(), vo.getDissentid())){
			
			logger.error(LogUtil.msg("CCQueryServiceImpl:creditReport", "请求参数不正确:" + JSON.toJSONString(vo)));
			resultVo.setCode(CodeConstant.REQ_PARAM_FAIL);
			resultVo.setMsg("获取用户征信报告参数不正确");
			return resultVo;
		}
		String certNo = vo.getCertno();
		String data = vo.toParams("GBK");
		logger.debug(LogUtil.msg("CCQueryServiceImpl:creditReport", "获取用户征信报告表请求数据：" + data));
		//个人征信系统中没有此人的征信记录
		int k = 0;
		for (int i = 0; i < 2; i++) {
			
			if(i == 1){
//				try {
//					vo.setCertno(URLDecoder.decode(vo.getCertno(),"GBK"));
//					vo.setName(URLDecoder.decode(vo.getName(),"GBK"));
//				} catch (UnsupportedEncodingException e) {
//					e.printStackTrace();
//				}
				data = vo.toParams("UTF-8");
				logger.info(LogUtil.msg("CCQueryServiceImpl:creditReport", "使用certno的UTF-8编码查询一次：" + data));
			}
			
			String requestUrl = ConfConstant.ccDomainUrl + ConfConstant.ccQueryCreditReportUrl + "?" + data;
			logger.debug(LogUtil.msg("CCQueryServiceImpl:creditReport", "获取用户征信报告请求url：" + requestUrl));
			Document document = null; 
			String sourceHtml = "";
			
			try {
				 
				 if(StrUtil.isNotNull(ConfConstant.ccTestPath)){
					 String fileName = "信用报告.html";
				     if(vo.getVertype().equals("21")){
				    	 fileName = "个人征信报告-简版.html";
				     }
					 document = Jsoup.parse(new File(ConfConstant.ccTestPath + fileName), "UTF-8");
					 
				 } else {
		     
					 document = JsoupUtil.get(requestUrl, "GBK", vo.getCookies());
					 logger.debug(LogUtil.msg("CCQueryServiceImpl:creditReport", "获取用户征信报告结果：" + document.html()));
					 
				 }
				 
				 if(document == null){
					 if(i == 0){
						 continue;
					 }	
					 logger.error(LogUtil.msg("CCQueryServiceImpl:creditReport", "征信中心查询申请表，征信中心没有返回任何信息"));
					 resultVo.setCode(CodeConstant.FAIL);
					 resultVo.setMsg("查询征信报告内容为空");
					 return resultVo;
				 }
				 
				 sourceHtml = document.html();
				 
				 if(StrUtil.isNotNull(sourceHtml)){
					 if(sourceHtml.indexOf("个人征信系统中没有此人的征信记录") != -1 && k < 3){
						 i --;
						 k ++;
						 logger.error(LogUtil.msg("CCQueryServiceImpl:creditReport", "个人征信系统中没有此人的征信记录:" + sourceHtml));
						 continue;
					 }
				 }
				 
				 String path = ConfConstant.fileCreditTempPath + DateUtil.format(new Date(), "yyyyMMdd");
				 FileUtil.createDir(path);
				 String fileName = path + File.separator + vo.getId() + ".html";
				 FileUtil.dataToFile(sourceHtml, fileName);
				 
			     String regx = "个人信用报告(.)*?";
			     
			     String str = document.getElementsMatchingText(regx).text();
			     
			     if(StrUtil.isNull(str)){//判断是否有查询记录
			    	 if(i == 0){
						 continue;
					 }
			    	 logger.error(LogUtil.msg("CCQueryServiceImpl:creditReport", "获取用户征信报告页面失败:"  + JSON.toJSONString(vo)));
					 resultVo.setCode(CodeConstant.DATA_NOT_EXSIT);
					 resultVo.setMsg("获取用户征信报告失败");
					 return resultVo;
			     }
			     
			     Elements elements = document.getElementsByTag("img");
			     if (elements != null && elements.size() > 0) {
			    	 elements.get(0).attr("src", "resources/images/qlogo.gif");
				     elements.get(1).attr("src", "resources/images/yz.gif");
				 }
			     try{
				     if(vo.getVertype().equals("21")){ 
				    	 Element element = document.getElementById("hang-5");
					     element.text(certNo);
				     }
				     if(vo.getVertype().equals("24")){ 
					     elements = document.getElementsMatchingOwnText("被查询者证件号码");
					     elements.get(0).parent().parent().nextElementSibling().child(2).text(certNo);
				     }
			     } catch (Exception e) {
						logger.error(LogUtil.msg("CCQueryServiceImpl:creditReport", "重写用户姓名失败"));
				 }
			     ResCCCreditReportVo resCCCreditReportVo = new ResCCCreditReportVo();
			     
			     elements = document.getElementsByAttributeValue("class", "font");
			     if(elements != null && elements.size() > 0){
			    	 
			    	 String text = elements.get(0).text();
			    	 logger.info(LogUtil.msg("CCQueryServiceImpl:creditReport", "查询编号：" + text));
			    	 if(text.indexOf("报告编号:") != -1){
			    		 String [] arr = text.split(":");
			    		 if(arr.length > 1){
			    			 resCCCreditReportVo.setCreditNo(arr[1]);
			    		 } 
			    	 }
			    	 
			     }
			     
			     elements = document.getElementsByTag("style");
			     document.getElementById("footertable").remove();
			     //document.body().getElementsByClass("warp").get(0).attr("style", "background-color: #ffffff;");
			     //String link = "<link href=\"resources/skins/css/print.css\" rel=\"stylesheet\" type=\"text/css\" media=\"print\" />";
			     String html = elements.outerHtml().replaceAll("930", "620") + document.body().html();
			     
			     resCCCreditReportVo.setHtml(html);	 
			     resultVo.setData(resCCCreditReportVo);
				 resultVo.setCode(CodeConstant.SUCCESS);
				 break ;
			} catch (Exception e) {
				
				if(i == 0){
					 continue;
				}
				if(StrUtil.isNotNull(sourceHtml)){//如果是解析异常，则将数据存入文件
					String path = ConfConstant.fileCreditTempPath + "exception";
					FileUtil.createDir(path);
					String fileName = path + File.separator + vo.getId() + ".html";
					FileUtil.dataToFile(sourceHtml, fileName);
				}
				
				logger.error(LogUtil.msg("CCQueryServiceImpl:creditReport", "获取用户征信报告表异常"), e);
				resultVo.setCode(CodeConstant.EXCEPTION);
				resultVo.setMsg("获取用户征信报告异常");
				return resultVo;
			}
		}
		return resultVo;
		
	}

	@Override
	public ResultVo<ResCCJusticeVo> justiceReport(ReqCCJusticeVo vo, HttpServletRequest request) {

		ResultVo<ResCCJusticeVo> resultVo = new ResultVo<>();
		
		if(vo == null || StrUtil.isNull(vo.getName(), vo.getCertno())){
			
			logger.error(LogUtil.msg("CCQueryServiceImpl:justiceReport", "请求参数不正确:"  + JSON.toJSONString(vo)));
			resultVo.setCode(CodeConstant.REQ_PARAM_FAIL);
			resultVo.setMsg("获取用户征信报告参数不正确");
			return resultVo;
		}
		
		String data = vo.toParams("GBK");
		logger.debug(LogUtil.msg("CCQueryServiceImpl:justiceReport", "获取用户征信报告表请求数据：" + data));
		
		for (int i = 0; i < 2; i++) {
		
			if(i == 1){
				data = vo.toParams("UTF-8");
				logger.info(LogUtil.msg("CCQueryServiceImpl:justiceReport", "使用certno的UTF-8编码再次查询：" + data));
			}
			
			String requestUrl = ConfConstant.ccDomainUrl + ConfConstant.ccQueryCreditReportUrl + "?" + data;
			logger.debug(LogUtil.msg("CCQueryServiceImpl:justiceReport", "获取用户征信报告请求url：" + requestUrl));
			Document document = null; 
			String sourceHtml = "";
			try {
				
				 
				 if(StrUtil.isNotNull(ConfConstant.ccTestPath)){
				 
					 document = Jsoup.parse(new File(ConfConstant.ccTestPath + "司法查询.-征信报告.html"), "UTF-8");
					 sourceHtml = document.html();
				 } else {
		     
					 document = JsoupUtil.post(requestUrl, data, "GBK", vo.getCookies());
					 sourceHtml = document.html();
					 logger.debug(LogUtil.msg("CCQueryServiceImpl:justiceReport", "获取用户征信报告异常结果：" + sourceHtml));
					 
				 }
			     
				 if(sourceHtml.indexOf("无法取得用户登录信息 ") != -1){
					 resultVo.setCode(CodeConstant.CREDIT_NO_LOGIN);
					 resultVo.setMsg("登录超时，请重新登录系统");
					 logger.error(LogUtil.msg("CCQueryServiceImpl:justiceReport", "司法查询，征信中心错误：无法取得用户登录信息"));
					 return resultVo;
				 }
				 
				 String path = ConfConstant.fileCreditTempPath + DateUtil.format(new Date(), "yyyyMMdd");
				 FileUtil.createDir(path);
				 String fileName = path + File.separator + vo.getId() + ".html";
				 FileUtil.dataToFile(sourceHtml, fileName);
				 
			     String regx = "个人信用报告(.)*?";
			     
			     String str = document.getElementsMatchingText(regx).text();
			     
			     if(StrUtil.isNull(str)){//判断是否有查询记录
			    	 if(i == 0){
			    		 continue;
			    	 }
			    	 logger.error(LogUtil.msg("CCQueryServiceImpl:justiceReport", "获取用户征信报告页面失败"));
					 resultVo.setCode(CodeConstant.DATA_NOT_EXSIT);
					 resultVo.setMsg("获取用户征信报告失败");
					 return resultVo;
			     }
			     
			     Elements elements = document.getElementsByTag("img").remove();
	
			     
	//		     try {
	//				 elements = document.getElementsMatchingOwnText("被查询者姓名");
	//				 elements.get(0).parent().parent().nextElementSibling().child(0).html("<font color=#0066cc><span class=high>"+ vo.getName() +"</span></font>");
	//			} catch (Exception e) {
	//				logger.error(LogUtil.msg("CCQueryServiceImpl:justiceReport", "重写用户姓名失败"));
	//			}
			     
			     
			     ResCCJusticeVo resCCCreditReportVo = new ResCCJusticeVo();
			     
			     elements = document.getElementsByTag("font");
			     if(elements != null && elements.size() > 0){
			    	 for (Element element : elements) {
			    		 String text = element.text();
				    	 if(text.indexOf("报告编号:") != -1){
				    		 String [] arr = text.split(":");
				    		 if(arr.length > 1){
				    			 resCCCreditReportVo.setCreditNo(arr[1]);
				    		 } 
				    		 break;
				    	 }
					}    	 
			    	 
			     }
			     
			     elements = document.getElementsByTag("style");
			     document.getElementsByTag("form").remove();
			     //document.body().getElementsByTag("body").get(0).attr("style", "background-color: #ffffff;");
			     String html = elements.outerHtml() + document.body().html().replaceAll("720", "620");
			     
			     resCCCreditReportVo.setHtml(html);	 
			     resultVo.setData(resCCCreditReportVo);
				 resultVo.setCode(CodeConstant.SUCCESS);
				 break;
			 } catch (Exception e) {
				if(i == 0){
		    		 continue;
		    	}
				if(StrUtil.isNotNull(sourceHtml)){//如果是解析异常，则将数据存入文件
					String path = ConfConstant.fileCreditTempPath + "exception";
					FileUtil.createDir(path);
					String fileName = path + File.separator + vo.getId() + ".html";
					FileUtil.dataToFile(sourceHtml, fileName);
				}
				
				logger.error(LogUtil.msg("CCQueryServiceImpl:justiceReport", "获取用户征信报告表异常"), e);
				resultVo.setCode(CodeConstant.EXCEPTION);
				resultVo.setMsg("获取用户征信报告异常");
				return resultVo;
			}
		}
		return resultVo;
	}

	@Override
	public ResultVo<ResCCCreditReportVo> againPrintReport(ReqCCCreditReportVo vo, HttpServletRequest request) {

        ResultVo<ResCCCreditReportVo> resultVo = new ResultVo<>();

		String certNo = vo.getCertno();
		logger.debug(LogUtil.msg("CCQueryServiceImpl:againPrintReport", "补打用户征信报告表请求数据：" + JSON.toJSONString(vo)));
		
		try {
			vo.setCertno(URLDecoder.decode(certNo,"GBK"));
			vo.setName(URLDecoder.decode(vo.getName(),"GBK"));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		Document document = null; 
		
		try {
	
			 String path = ConfConstant.fileCreditTempPath + DateUtil.format(new Date(), "yyyyMMdd");

			 String fileName = path + File.separator + vo.getId() + ".html";
		     
			 document = Jsoup.parse(new File(fileName), "UTF-8");
			 
			 if(document == null){
				 logger.error(LogUtil.msg("CCQueryServiceImpl:againPrintReport", "没有该用户的补打报告"));
				 resultVo.setCode(CodeConstant.FAIL);
				 resultVo.setMsg("查询征信报告内容为空");
				 return resultVo;
			 }
			 
		     String regx = "个人信用报告(.)*?";
		     
		     String str = document.getElementsMatchingText(regx).text();
		     
		     if(StrUtil.isNull(str)){//判断是否有查询记录
		    	 logger.error(LogUtil.msg("CCQueryServiceImpl:againPrintReport", "获取用户征信报告页面失败:"  + JSON.toJSONString(vo)));
				 resultVo.setCode(CodeConstant.DATA_NOT_EXSIT);
				 resultVo.setMsg("获取用户征信报告失败");
				 return resultVo;
		     }
		     
		     Elements elements = document.getElementsByTag("img");
		     if (elements != null && elements.size() > 0) {
		    	 elements.get(0).attr("src", "resources/images/qlogo.gif");
			     elements.get(1).attr("src", "resources/images/yz.gif");
			 }
		     
		     try{
			     if(vo.getVertype().equals("21")){ 
			    	 Element element = document.getElementById("hang-5");
				     element.text(certNo);
			     }
			     if(vo.getVertype().equals("24")){ 
				     elements = document.getElementsMatchingOwnText("被查询者证件号码");
				     elements.get(0).parent().parent().nextElementSibling().child(2).text(certNo);
			     }
		     } catch (Exception e) {
					logger.error(LogUtil.msg("CCQueryServiceImpl:againPrintReport", "重写用户证件号码失败"));
			 }
		     
		     ResCCCreditReportVo resCCCreditReportVo = new ResCCCreditReportVo();
		     
		     elements = document.getElementsByAttributeValue("class", "font");
		     if(elements != null && elements.size() > 0){
		    	 
		    	 String text = elements.get(0).text();
		    	 logger.info(LogUtil.msg("CCQueryServiceImpl:againPrintReport", "查询编号：" + text));
		    	 if(text.indexOf("报告编号:") != -1){
		    		 String [] arr = text.split(":");
		    		 if(arr.length > 1){
		    			 resCCCreditReportVo.setCreditNo(arr[1]);
		    		 } 
		    	 }
		    	 
		     }
		     
		     elements = document.getElementsByTag("style");
		     document.getElementById("footertable").remove();
		     String html = elements.outerHtml().replaceAll("930", "620") + document.body().html();
		     resCCCreditReportVo.setId(vo.getId());
		     resCCCreditReportVo.setHtml(html);	 
		     resultVo.setData(resCCCreditReportVo);
			 resultVo.setCode(CodeConstant.SUCCESS);
	
		} catch (Exception e) {

			logger.error(LogUtil.msg("CCQueryServiceImpl:againPrintReport", "补打用户征信报告表异常"), e);
			resultVo.setCode(CodeConstant.EXCEPTION);
			resultVo.setMsg("补打用户征信报告异常");
			return resultVo;
		}
		
		return resultVo;
	}
	
	

}
